<?php

declare(strict_types=1);

namespace App\Service;

class AreainfoService extends BaseService
{

    /**
     * 获取地区模型 或 地区信息
     * @param int|array $id
     * @param bool $assoc
     * @return array
     */
    public function getAreainfo($id, $assoc = false)
    {
        if (is_array($id)) {
            // 获取缓存模型
            $instances = $this->getModelInstance()->findManyFromCache($id);
            $instances_return = empty($instances) ? [] : $instances->toArray();
            // 缓存不完整，查询并更新
            if (count($instances_return) !== count($id)) {
                foreach ($id as $v) {
                    if (!in_array($v, array_column($instances_return, 'id'))) {
                        $new_instance = $this->getModelInstance()->find($id);
                        if (!empty($new_instance)) {
                            $instances_return[] = $new_instance->toArray();
                        }
                    }
                }
            }
        } else {
            $instances = $this->getModelInstance()->findFromCache($id);
            if (empty($instances)) {
                $instances = $this->getModelInstance()->find($id);
            }
            if ($assoc) {
                $instances_return = empty($instances) ? [] : $instances->toArray();
            } else {
                $instances_return = $instances;
            }
        }
        return $instances_return;
    }

    /**
     * 获取父级列表
     * @param $id
     * @param array $arr
     * @return array
     */
    public function getFullAddress($id, $arr = [])
    {
        if (empty($id)) {
            return $arr;
        }
        $area = $this->getModelInstance()->findFromCache($id);
        if (empty($area)) {
            $area = $this->getModelInstance()->find($id);
        }
        // 调用自己获取父类
        if (!empty($area)) {
            $area = $area->toArray();
            if ($area['pid'] == 0) {
                return $arr;
            }
            $arr = array_merge($this->getFullAddress($area['pid'], $arr), $arr);
            $arr[] = $area;
        }
        return $arr;
    }
}